<?php

namespace Biz\service;

use Biz\cache\SToken;
use Biz\model\ShopAuth as ShopAuthModel;
use Doraemon\cache\RedisCache;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\tools\Log as tLog;
/**
 * @deprecated
 */
class ShopRegister
{

    use _Async;

    const EMAIL_CODE_KEY_PREFIX_ = 'email_code_';


    /**
     * 发送邮件验证码
     * @param $email
     * @param $token
     * @return bool
     * @throws \Exception
     */
    public static function sendCode($email, $token)
    {
        if ($email) {
            $authInfo = ShopAuthModel::getByEmail($email);
            if ($authInfo) {
                throw new \Exception('该邮箱已被注册，请直接登录');
            }
            ShopRegister::checkAppIsLogin($token);
            $code = self::rand_str(6);
            $exprise = RedisCache::ttl(self::EMAIL_CODE_KEY_PREFIX_ . $email);
            if ($exprise && (10800 - $exprise) < 30) {
                throw new \Exception('验证码发送太频繁，请稍后再试');
            }
            RedisCache::setex(self::EMAIL_CODE_KEY_PREFIX_ . $email, 10800, $code);
            self::_async($email, $code);
            return true;
        }
        return false;
    }

    public static function _async_sendCode($email, $code)
    {
        $result = MessageSend::sendEmail($email, 'verify_email_address', ['code' => $code]);
        if (!$result) {
            tLog::warning('发送邮件失败', ['email' => $email, 'result' => $result]);
        }
    }

    public static function checkCode($email, $code)
    {
        $cachCode = RedisCache::get(self::EMAIL_CODE_KEY_PREFIX_ . $email);
        return ($cachCode == $code);
    }

    /**
     * 设置邮箱
     * @param $email
     * @param $code
     * @param $password
     * @return mixed
     * @throws \Exception
     */
    public static function setEmail($uid, $email, $code, $password)
    {
        $password = ShopAuth::password($password);
        $mailCode = RedisCache::get(self::EMAIL_CODE_KEY_PREFIX_ . $email);
        if ($code == $mailCode) {
            $result = ShopAuth::setAuth($uid, $email, $password);
            if ($result) {
                return $uid;
            }
            return $result;
        } else {
            throw new \Exception('验证码不正确，请重新输入');
        }
        return false;
    }


    /**
     * 检查app手机账号是否登陆，注册流程使用
     * @throws \Exception
     */
    public static function checkAppIsLogin($token)
    {
        $appUid = SToken::getTokenValue($token, SToken::TOKEN_APPUID);
        if (!$appUid) {
            throw new \Exception('未登录好好住App账号或登陆状态失效');
        }
        return $appUid;
    }


    private static function rand_str($length = 10, $is_string = false)
    {
        if ($is_string) {
            $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        } else {
            $str = '0123456789';
        }
        $str = str_shuffle($str);
        return substr($str, 0, $length);
    }
}